package com.miao.teacher.ui;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.umeng.analytics.MobclickAgent;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.Window;
import android.widget.Toast;

public class BaseFragmentActivity extends FragmentActivity{
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	}
	private ProgressDialog mPd;

	private static final int DOWNLOAD_SUCCESS = 100001;
	private static final int DOWNLOAD_FAILED = 1000002;

	public static final String APK_NAME = "miao_teacher.apk";
	
	// 通知子类 接收到UI更新消息
	protected void RecMsgFromHandler(Message msg) {

	}

	// UI消息 更新UI
	protected Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {// 此方法在ui线程运行
			if (msg.what == DOWNLOAD_SUCCESS) {
				if (mPd != null) {
					if (mPd.isShowing()) {
						mPd.dismiss();
					}
				}
			} else if (msg.what == DOWNLOAD_FAILED) {
				if (mPd != null) {
					if (mPd.isShowing()) {
						mPd.dismiss();
					}
				}
			} else {
				RecMsgFromHandler(msg);
			}
		}
	};
	protected void downLoadApk(final String url) {
		mPd = new ProgressDialog(BaseFragmentActivity.this);
		mPd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mPd.setMessage("版本更新中");
		mPd.setProgressNumberFormat("%1d kb/%2d kb");
		// mPd.incrementProgressBy(0);
		mPd.show();
		new Thread() {
			public void run() {
				try {
					File file = getFileFromServer(url, mPd);
					mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);
					installApk(file);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 
	 * @param file
	 *            下载apk文件
	 */
	private void installApk(File file) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		try {
			startActivity(intent);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}
	/*
	 * 获取屏幕宽度 px
	 */
	protected int getXPx() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		dm = getApplicationContext().getResources().getDisplayMetrics();
		return dm.widthPixels;
	}

	/*
	 * 获取屏幕高度 px
	 */
	protected int getYPx() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		dm = getApplicationContext().getResources().getDisplayMetrics();
		return dm.heightPixels;
	}
	/*
	 * dpi转px
	 */
	public int dip2px(float dipValue) {
		final float scale = getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}
	/**
	 * 
	 * @param path
	 *            文件下载路径
	 * @param pd
	 *            进度条
	 * @return
	 * @throws Exception
	 *             异常
	 */
	private File getFileFromServer(String path, ProgressDialog pd)
			throws Exception {
		// 如果相等的话表示当前的sdcard挂载在手机上的并且是可用的
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			// 获取文件的大小
			// String totalSize = bytes2kb(conn.getContentLength());
			pd.setMax((int) byteToKB(conn.getContentLength()));
			// pd.setMax(conn.getContentLength());
			InputStream is = conn.getInputStream();
			File file = new File(Environment.getExternalStorageDirectory(),
					APK_NAME);
			FileOutputStream fos = new FileOutputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			byte[] buffer = new byte[1024];
			int len;
			int total = 0;
			while ((len = bis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				total += len;
				// Integer.parseInt(bytes2kb(total));
				pd.setProgress((int) byteToKB(total));
				// pd.setProgress(total);
			}
			fos.close();
			bis.close();
			is.close();
			return file;
		} else {
			return null;
		}
	}

	public long byteToKB(long byteTransform) {
		long mb = 1024L;
		return byteTransform / mb;
	}
	/*
	 * Toast显示消息
	 */
	protected void ToastShowMsg(String msg) {
		Toast.makeText(this, msg, 3000).show();
	}

	protected void ToastShowMsg(int resId) {
		Toast
				.makeText(this, getResources().getString(resId),
						3000).show();
	}
}
